/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BARootViewController.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 14/08/13.
//  Copyright (c) 2013 Redia A/S. All rights reserved.
//

#import "BARootViewController.h"
#import "BACustomNavigationBar.h"
#import "BACustomNavigationController.h"
#import "BALibrarySelectionViewController.h"
#import "BAUserSearchViewController.h"
#import "BAPatronHoldingsViewController.h"
#import "BACustomTabBarController.h"
#import "UIImage+MultiplyColor.h"
#import "BALibrarySettings.h"
#import "BAUtils.h"
#import "MWFSlideNavigationViewController.h"
#import "BANewsEventsViewController.h"
#import "BAOpeningHoursViewController.h"
#import "BANewsEventsViewController_iPad.h"
#import "BAUserSearchViewController_iPad.h"
#import "BASlideInViewController.h"
#import "BAFlyoutMenuViewController.h"
#import "BAScanFrontViewController.h"
#import "LazyLoadManager.h"
#import "BALoginViewController.h"
#import "BASettingsUserDefaultsKeys.h"
#import "BAUserGuideViewController.h"
#import "BAIntroGuideViewController.h"
#import "BAPatronSettings.h"

#ifdef BA_LIBRARIAN_BUILD
#import "LBLibrarianSearchViewController.h"
#import "LBLibrarianMaterialViewController.h"
#import "LBLibrarianSearchViewController_iPad.h"
#endif

#ifdef BA_IMF_BUILD
#import "IMFHomeViewController.h"
#import "IMFHomeViewController_iPad.h"
#import "IMFAddMaterialToIMFPackageViewController.h"
#import "IMFAddMaterialToIMFPackageiPadViewController.h"
#import "IMFNotificationPopupViewController.h"
#endif


@interface BARootViewController() {
    BAUserSearchViewController_iPad* userSearchViewControllerIPad;
    BASlideInViewController* userSearchSlideInIPad;
    BAUserGuideViewController* currentUserGuideViewController;
    UIView* currentUserGuideSuperView;
    BAIntroGuideViewController* introGuideViewController;
    
    UIView* transparentUserInterActionCoverView;
    
    NSString* newSupportRedirectUrlString;
    
}

@property (nonatomic) BARootViewAppState currentAppState;

@end

@implementation BARootViewController

SINGLETON_IMPL_GCD(BARootViewController)

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithWhite:228.0/255.0 alpha:1]; //  [UIColor grayColor];

    BOOL appHasOpenedFirstTime = [[NSUserDefaults standardUserDefaults] boolForKey:BASETTINGS_APP_HAS_OPENED_FIRST_TIME];
    
    if (!appHasOpenedFirstTime) {
        _currentAppState = BARootViewAppStateIntroGuideMode;
        
        introGuideViewController = [BAIntroGuideViewController new];
        [self addChildViewController:introGuideViewController];
        [self.view addSubview:introGuideViewController.view];
        introGuideViewController.view.frame = self.view.bounds;
        
    } else {
        _currentAppState = BARootViewAppStateInitialSelectionAndLoginMode;
        [self switchToLibrarySelectionWithShowingLoginScreen:NO];
    }

    self.slideNavigationViewController.dataSource = self;
    self.slideNavigationViewController.delegate = self;
    
    transparentUserInterActionCoverView = [[UIView alloc] initWithFrame:self.view.bounds];
    transparentUserInterActionCoverView.userInteractionEnabled=YES;
    transparentUserInterActionCoverView.backgroundColor=[UIColor clearColor];
    transparentUserInterActionCoverView.opaque=NO;
    //NB: transparentUserInterActionCoverView is only added to view hierachy when it is used
    UIGestureRecognizer* tapgest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeFlyoutMenu:)];
    [transparentUserInterActionCoverView  addGestureRecognizer:tapgest];
    UISwipeGestureRecognizer* swipegest = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(closeFlyoutMenu:)];
    [transparentUserInterActionCoverView addGestureRecognizer:swipegest];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(debugServerSetupChanged:)
                                                 name:BA_DEBUG_SERVER_SELECTOR_RELOAD_LIBRARY_LIST
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:IMF_SWITCH_TO_PACKAGE_TAB object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        if (self.currentAppState == BARootViewAppStateImfEditorMode || self.currentAppState == BARootViewAppStateImfEditorWithLibrarianSearchMode) {
            
            //This is a hack to ensure that the tab is ready to be presented:
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [rootLevelTabBarController setSelectedIndex:0];
            });
        }
    }];
    
    NSBundle* mainbundle = [NSBundle mainBundle];

    newSupportRedirectUrlString=nil;
    [BARPCManager isSupportedAsyncFromView:self
                                    device:[[UIDevice currentDevice] model]
                                   appName:[mainbundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]
                                   version:[mainbundle objectForInfoDictionaryKey:@"CFBundleVersion"]
                                 osVersion:[[UIDevice currentDevice] systemVersion]
                               resultBlock:^(BASupportInfo *result) {
                                   if (result!=nil) {
                                       
                                       if (result.isSupported) {
                                           DLog(@"isSupported: true");
                                       } else {
                                           NSString* message = @"Denne app er ikke længere understøttet";
                                           
                                           if ([result.userMessage length]>0) {
                                               message = result.userMessage;
                                           }
                                           if ([result.redirectUrl length]>0) {
                                               message = [message stringByAppendingString:@". Klik på 'Mere info' for oplysninger om opgradering."];
                                           }
                                           newSupportRedirectUrlString = result.redirectUrl;
                                           
                                           UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Systembesked"
                                                                                           message:message
                                                                                          delegate:self
                                                                                 cancelButtonTitle:@"OK"
                                                                                 otherButtonTitles:([result.redirectUrl length]>0 ? @"Mere info" : nil), nil];
                                           [alert show];
                                       }
                                   }
                               } errorBlock:^(int errorCode, NSString *errorMessage) {
                                   NSLog(@"Error contacting server when requesting 'isSupported'");
                               }];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1 && [newSupportRedirectUrlString length]>0) {
        NSURL* url = [NSURL URLWithString:newSupportRedirectUrlString];
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)dismissIntroGuide:(id)sender
{
    [self switchToLibrarySelectionWithShowingLoginScreen:NO];
    [self.view bringSubviewToFront:introGuideViewController.view];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:BASETTINGS_APP_HAS_OPENED_FIRST_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [self performSelector:@selector(delayedDismissIntroGuideAnimation) withObject:Nil afterDelay:0.1];
}

- (void)delayedDismissIntroGuideAnimation
{
    CGRect animframe = introGuideViewController.view.frame;
    animframe.origin.x -= animframe.size.width;
    [UIView animateWithDuration:0.25
                     animations:^{
                         introGuideViewController.view.frame=animframe;
                         introGuideViewController.view.alpha=0;
                     }
                     completion:^(BOOL finished) {
                         [introGuideViewController.view removeFromSuperview];
                         [introGuideViewController removeFromParentViewController];
                     }];

}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_DEBUG_SERVER_SELECTOR_RELOAD_LIBRARY_LIST object:nil];
}

- (void)debugServerSetupChanged:(id)sender
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:BASETTINGS_LIBRARYNAMES_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self switchToLibrarySelectionWithShowingLoginScreen:NO];
}

- (NSUInteger)supportedInterfaceOrientations
{
    if (RD_IS_IPAD) {
        return UIInterfaceOrientationMaskLandscape;
    } else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

- (void)switchToLibrarySelectionWithShowingLoginScreen:(BOOL)doShowLogin
{
    _currentAppState = BARootViewAppStateInitialSelectionAndLoginMode;
    
    if (rootLevelNavigationController == nil) {
        rootLevelNavigationController = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
        [self addChildViewController:rootLevelNavigationController];
        [self.view addSubview:rootLevelNavigationController.view];
        rootLevelNavigationController.view.frame = self.view.bounds;
    }
    if (rootLevelTabBarController) {
        [rootLevelTabBarController.view removeFromSuperview];
        [rootLevelTabBarController removeFromParentViewController];
        rootLevelTabBarController = nil;
        [self addChildViewController:rootLevelNavigationController];
        [self.view addSubview:rootLevelNavigationController.view];
    }
    
    if (doShowLogin) {
        [rootLevelNavigationController setViewControllers:@[ [[BALibrarySelectionViewController alloc] initWithNibName:@"BALibrarySelectionViewController" bundle:nil],
                                                             [[BALoginViewController alloc] initWithNibName:@"BALoginViewController" bundle:nil]
                                                             ]];
    } else {
        [rootLevelNavigationController setViewControllers:@[ [[BALibrarySelectionViewController alloc] initWithNibName:@"BALibrarySelectionViewController" bundle:nil] ]];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)switchToMainTabBarAppMode
{
    if ([[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary] || [[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
        [self switchToLibrarianOrImfEditorAppMode];

    } else if ([[BALibrarySettings instance] isUserLibraryModeAllowed]) {
        [self switchToUserLibraryAppMode];

    } else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Ingen adgang"
                                                        message:@"Den angivne bruger har ikke de nødvendige rettigheder til at logge ind på dette bibliotek."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (void)switchToUserLibraryAppMode
{
    [rootLevelNavigationController.view removeFromSuperview];
    [rootLevelTabBarController.view removeFromSuperview];
    [rootLevelTabBarController removeFromParentViewController];
    rootLevelTabBarController = [[BACustomTabBarController alloc] init];
    [self addChildViewController:rootLevelTabBarController];
    [rootLevelTabBarController.view setFrame:self.view.bounds];
    [self.view addSubview:rootLevelTabBarController.view];
    
    //preload opening hours logo before anything else
    NSString* mainLogoUrl = [BAOpeningHoursViewController getOpeningHoursResizedLogoUrl];
    if (mainLogoUrl) {
        [[LazyLoadManager instance] lazyLoadUIImageFromUrl:mainLogoUrl
                                         setScaleforRetina:YES
                                                 onSuccess:^(UIImage *image) {
                                                     DLog(@"preloaded openinghours logo");
                                                 } onError:^(LazyLoaderErrorCode errorCode, NSString *errorMessage) {
                                                 }];
    }
    
    if (RD_IS_IPAD) {
        NSMutableArray* iPadTabBarViewControllers = [NSMutableArray new];
        
        BANewsEventsViewController_iPad *news = [[BANewsEventsViewController_iPad alloc] initWithNibName:@"BANewsEventsViewController_iPad" bundle:nil];
        BASlideInViewController* news_slide = [[BASlideInViewController alloc] initWithNibName:@"BASlideInViewController" bundle:nil];
        [news_slide setRootViewController:news];
        [self updateTabBarItem:news_slide.tabBarItem withImageName:@"tab-news"];

        [iPadTabBarViewControllers addObject:news_slide];
        
        
        BACustomNavigationController* patron_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
        BAPatronHoldingsViewController* phvc = [[BAPatronHoldingsViewController alloc] initWithNibName:@"BAPatronHoldingsViewController_iPad" bundle:nil];
        [patron_nav setViewControllers:@[phvc]];
        [self updateTabBarItem:patron_nav.tabBarItem withImageName:@"tab-patron"];
        
        [iPadTabBarViewControllers addObject:patron_nav];
        
        userSearchViewControllerIPad = [BAUserSearchViewController_iPad new];
        userSearchSlideInIPad = [[BASlideInViewController alloc] initWithNibName:@"BASlideInViewController" bundle:nil];
        [userSearchSlideInIPad setRootViewController:userSearchViewControllerIPad];
        [self updateTabBarItem:userSearchSlideInIPad.tabBarItem withImageName:@"tab-search"];
        
        [iPadTabBarViewControllers addObject:userSearchSlideInIPad];

        if ([BALibrarySettings instance].isScannerEnabled) {
            BAScanFrontViewController* scanner = [[BAScanFrontViewController alloc] initWithNibName:@"BAScanFrontViewController" bundle:nil];
            [self updateTabBarItem:scanner.tabBarItem withImageName:@"tab-scan"];
            BACustomNavigationController* scan_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
            [scan_nav setViewControllers:@[scanner]];
            
            [iPadTabBarViewControllers addObject:scan_nav];
        }
        
        
        BAOpeningHoursViewController *openingHours = [[BAOpeningHoursViewController alloc] initWithNibName:@"BAOpeningHoursViewController" bundle:nil];
        BASlideInViewController* opening_slide = [[BASlideInViewController alloc] initWithNibName:@"BASlideInViewController" bundle:nil];
        [opening_slide setRootViewController:openingHours];
        [self updateTabBarItem:opening_slide.tabBarItem withImageName:@"tab-hours"];
        
        [iPadTabBarViewControllers addObject:opening_slide];
        
        [rootLevelTabBarController setViewControllers:iPadTabBarViewControllers];
        
        //[rootLevelTabBarController setViewControllers:@[news_slide, search_slide]];
        
        //#######
        //Removed 18/2 by Nikolaj: We are not using this!
//        rootLevelTabBarController.delegate = self;
        //#######
        
    } else {
        
        NSMutableArray* iPhoneTabBarViewControllers = [NSMutableArray new];

        BANewsEventsViewController *news = [[BANewsEventsViewController alloc] initWithNibName:@"BANewsEventsViewController" bundle:nil];
        [self updateTabBarItem:news.tabBarItem withImageName:@"tab-news"];
        BACustomNavigationController* news_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
        [news_nav setViewControllers:@[news]];
        [iPhoneTabBarViewControllers addObject:news_nav];

        
        BACustomNavigationController* patron_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
        BAPatronHoldingsViewController* phvc = [[BAPatronHoldingsViewController alloc] initWithNibName:@"BAPatronHoldingsViewController_iPhone" bundle:nil];
        [patron_nav setViewControllers:@[phvc]];
        [self updateTabBarItem:patron_nav.tabBarItem withImageName:@"tab-patron"];
        [iPhoneTabBarViewControllers addObject:patron_nav];
        
        BAUserSearchViewController* svc = [BAUserSearchViewController new];
        BACustomNavigationController* search_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
        [search_nav setViewControllers:@[svc]];
        [self updateTabBarItem:search_nav.tabBarItem withImageName:@"tab-search"];
        [iPhoneTabBarViewControllers addObject:search_nav];

        if ([BALibrarySettings instance].isScannerEnabled) {
            BAScanFrontViewController* scanner = [[BAScanFrontViewController alloc] initWithNibName:@"BAScanFrontViewController" bundle:nil];
            [self updateTabBarItem:scanner.tabBarItem withImageName:@"tab-scan"];
            BACustomNavigationController* scan_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
            [scan_nav setViewControllers:@[scanner]];
            [iPhoneTabBarViewControllers addObject:scan_nav];
        }
  
        BAOpeningHoursViewController *openingHours = [[BAOpeningHoursViewController alloc] initWithNibName:@"BAOpeningHoursViewController" bundle:nil];
        [self updateTabBarItem:openingHours.tabBarItem withImageName:@"tab-hours"];
        BACustomNavigationController* opening_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
        [opening_nav setViewControllers:@[openingHours]];
        [iPhoneTabBarViewControllers addObject:opening_nav];
        
        [rootLevelTabBarController setViewControllers:iPhoneTabBarViewControllers];
    }
    
    [rootLevelTabBarController setSelectedIndex:0];
    
    BOOL appHasShownHomeScreenFirstTime = [[NSUserDefaults standardUserDefaults] boolForKey:BASETTINGS_APP_HAS_SHOWN_HOME_SCREEN_FIRST_TIME];
    if (!appHasShownHomeScreenFirstTime) {
        [self showUserGuide];
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:BASETTINGS_APP_HAS_SHOWN_HOME_SCREEN_FIRST_TIME];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    }
}

- (void)switchToLibrarianOrImfEditorAppMode
{
#if defined(BA_LIBRARIAN_BUILD) || defined(BA_IMF_BUILD)
    //BALibrarySettings* librarySettings = [BALibrarySettings instance];
    BAPatronSettings* patronSettings = [BAPatronSettings instance];
    
    _currentAppState = BARootViewAppStateLibrarianSearchMode;
    
    if ([patronSettings isUserAllowedIMFEditorAccessForCurrentLibrary]) {
        //IMF enabled for library
        if ([patronSettings isUserAllowedLibrarianAccessForCurrentLibrary]) {
            //imf + librarian
            _currentAppState = BARootViewAppStateImfEditorWithLibrarianSearchMode;
            
        } else {
            //imf only
            _currentAppState = BARootViewAppStateImfEditorMode;
            
        }
    } else {
        //no IMF
        if ([patronSettings isUserAllowedLibrarianAccessForCurrentLibrary]) {
            //librarian only
            _currentAppState = BARootViewAppStateLibrarianSearchMode;
            
        } else {
            //neither - this is disallowed. go to user mode
            _currentAppState = BARootViewAppStateUserTabBarMode;
            [self switchToUserLibraryAppMode];
            
        }
    }

    
    [rootLevelNavigationController.view removeFromSuperview];
    [rootLevelTabBarController.view removeFromSuperview];
    [rootLevelTabBarController removeFromParentViewController];
    rootLevelTabBarController = [[BACustomTabBarController alloc] init];
    rootLevelTabBarController.delegate = self;
    [self addChildViewController:rootLevelTabBarController];
    [rootLevelTabBarController.view setFrame:self.view.bounds];
    [self.view addSubview:rootLevelTabBarController.view];
    
    int selectedTabBarIndex = 0;
    
    if (RD_IS_IPAD) {
        NSMutableArray* librarianiPadTabBarViewControllers = [NSMutableArray new];
        
        if (_currentAppState == BARootViewAppStateImfEditorMode || _currentAppState==BARootViewAppStateImfEditorWithLibrarianSearchMode) {
            
            IMFHomeViewController_iPad* ihvc = [[IMFHomeViewController_iPad alloc] initWithNibName:@"IMFHomeViewController_iPad" bundle:nil];
            BASlideInViewController* ihvc_slide = [[BASlideInViewController alloc] initWithNibName:@"BASlideInViewController" bundle:nil];
            [ihvc_slide setRootViewController:ihvc];
            [self updateTabBarItem:ihvc_slide.tabBarItem withImageName:@"tab-imf"];
            
            [librarianiPadTabBarViewControllers addObject:ihvc_slide];
            
            [ihvc view]; //this view MUST be loaded for notifications to work (add to package)
        }
        
        if ([BALibrarySettings instance].isScannerEnabled) {
            BAScanFrontViewController* scanner = [[BAScanFrontViewController alloc] initWithNibName:@"BAScanFrontViewController" bundle:nil];
            [self updateTabBarItem:scanner.tabBarItem withImageName:@"tab-scan"];
            BACustomNavigationController* scan_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
            [scan_nav setViewControllers:@[scanner]];
            
            [librarianiPadTabBarViewControllers addObject:scan_nav];
        }
        
        if (_currentAppState == BARootViewAppStateLibrarianSearchMode || _currentAppState==BARootViewAppStateImfEditorWithLibrarianSearchMode) {
            // librarian dev: use slide-in and BALibrarianSearchViewController_iPad
            
            LBLibrarianSearchViewController_iPad* lsvc = [[LBLibrarianSearchViewController_iPad alloc] initWithNibName:@"LBLibrarianSearchViewController_iPad" bundle:nil];
            BASlideInViewController* lsvc_slide = [[BASlideInViewController alloc] initWithNibName:@"BASlideInViewController" bundle:nil];
            [lsvc_slide setRootViewController:lsvc];
            [self updateTabBarItem:lsvc_slide.tabBarItem withImageName:@"tab-search"];
            [librarianiPadTabBarViewControllers addObject:lsvc_slide];
            
            /* old code
            BALibrarianSearchViewController* svc = [BALibrarianSearchViewController new];
            BACustomNavigationController* search_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
            [search_nav setViewControllers:@[svc]];
            [self updateTabBarItem:search_nav.tabBarItem withImageName:@"tab-search"];
            [librarianiPadTabBarViewControllers addObject:search_nav];
            */
            
            selectedTabBarIndex = [librarianiPadTabBarViewControllers count]-1; //NB: this will be the selected tab!
            
        } else {
            userSearchViewControllerIPad = [BAUserSearchViewController_iPad new];
            userSearchSlideInIPad = [[BASlideInViewController alloc] initWithNibName:@"BASlideInViewController" bundle:nil];
            [userSearchSlideInIPad setRootViewController:userSearchViewControllerIPad];
            [self updateTabBarItem:userSearchSlideInIPad.tabBarItem withImageName:@"tab-search"];
            
            [librarianiPadTabBarViewControllers addObject:userSearchSlideInIPad];
        }
        
        if (_currentAppState == BARootViewAppStateImfEditorMode || _currentAppState==BARootViewAppStateImfEditorWithLibrarianSearchMode) {
            BAOpeningHoursViewController *openingHours = [[BAOpeningHoursViewController alloc] initWithNibName:@"BAOpeningHoursViewController" bundle:nil];
            BASlideInViewController* opening_slide = [[BASlideInViewController alloc] initWithNibName:@"BASlideInViewController" bundle:nil];
            [opening_slide setRootViewController:openingHours];
            [self updateTabBarItem:opening_slide.tabBarItem withImageName:@"tab-hours"];
            
            [librarianiPadTabBarViewControllers addObject:opening_slide];
        }
        
        [rootLevelTabBarController setViewControllers:librarianiPadTabBarViewControllers];
        [rootLevelTabBarController setSelectedIndex:selectedTabBarIndex];
        
    } else {
    
        NSMutableArray* librarianiPhoneTabBarViewControllers = [NSMutableArray new];
        
        if (_currentAppState == BARootViewAppStateImfEditorMode || _currentAppState==BARootViewAppStateImfEditorWithLibrarianSearchMode) {
            BACustomNavigationController* imf_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
            IMFHomeViewController* ihvc = [[IMFHomeViewController alloc] initWithNibName:@"IMFHomeViewController" bundle:nil];
            [imf_nav setViewControllers:@[ihvc]];
            [self updateTabBarItem:imf_nav.tabBarItem withImageName:@"tab-imf"];
            [librarianiPhoneTabBarViewControllers addObject:imf_nav];
            
            [ihvc view]; //this view MUST be loaded for notifications to work (add to package)
        }
        
        
        if ([BALibrarySettings instance].isScannerEnabled) {
            BAScanFrontViewController* scanner = [[BAScanFrontViewController alloc] initWithNibName:@"BAScanFrontViewController" bundle:nil];
            [self updateTabBarItem:scanner.tabBarItem withImageName:@"tab-scan"];
            BACustomNavigationController* scan_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
            [scan_nav setViewControllers:@[scanner]];
            [librarianiPhoneTabBarViewControllers addObject:scan_nav];
        }
        
        if (_currentAppState == BARootViewAppStateLibrarianSearchMode || _currentAppState==BARootViewAppStateImfEditorWithLibrarianSearchMode) {
            LBLibrarianSearchViewController* svc = [LBLibrarianSearchViewController new];
            BACustomNavigationController* search_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
            [search_nav setViewControllers:@[svc]];
            [self updateTabBarItem:search_nav.tabBarItem withImageName:@"tab-search"];
            [librarianiPhoneTabBarViewControllers addObject:search_nav];
            selectedTabBarIndex = [librarianiPhoneTabBarViewControllers count]-1; //NB: this will be the selected tab!
            
        } else {
            BAUserSearchViewController* svc = [BAUserSearchViewController new];
            BACustomNavigationController* search_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
            [search_nav setViewControllers:@[svc]];
            [self updateTabBarItem:search_nav.tabBarItem withImageName:@"tab-search"];
            [librarianiPhoneTabBarViewControllers addObject:search_nav];
            
        }
        
        if (_currentAppState == BARootViewAppStateImfEditorMode || _currentAppState==BARootViewAppStateImfEditorWithLibrarianSearchMode) {
            BAOpeningHoursViewController *openingHours = [[BAOpeningHoursViewController alloc] initWithNibName:@"BAOpeningHoursViewController" bundle:nil];
            [self updateTabBarItem:openingHours.tabBarItem withImageName:@"tab-hours"];
            BACustomNavigationController* opening_nav = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
            [opening_nav setViewControllers:@[openingHours]];
            [librarianiPhoneTabBarViewControllers addObject:opening_nav];
        }
        
        [rootLevelTabBarController setViewControllers:librarianiPhoneTabBarViewControllers];
        [rootLevelTabBarController setSelectedIndex:selectedTabBarIndex];
    }
#endif
}

- (void)updateTabBarItem:(UITabBarItem*)tabbar_item withImageName:(NSString*)name
{
    UIImage *image = [UIImage imageNamed:name multiplyWithColor:[UIColor colorWithWhite:102.0/255.0 alpha:1]];
    UIImage *selected = [UIImage imageNamed:name multiplyWithColor:[[BALibrarySettings instance] getCustomerColorNormal]];
    
    if ([[BAUtils instance] iOSMajorVersion] > 6) {
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        selected = [selected imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    
    [tabbar_item setImage:image];
    [tabbar_item setSelectedImage:selected];
    [tabbar_item setImageInsets:UIEdgeInsetsMake(5, 0, -5, 0)];

}


#pragma mark - Flyout menu

- (void)flyoutMenuClicked
{
    if (self.slideNavigationViewController.currentSlideDirection == MWFSlideDirectionNone) {
        [self.slideNavigationViewController slideWithDirection:MWFSlideDirectionLeft];
    }
    else {
        [self.slideNavigationViewController slideWithDirection:MWFSlideDirectionNone];
    }
    
}

- (UIViewController *)slideNavigationViewController:(MWFSlideNavigationViewController *)controller
                     viewControllerForSlideDirecton:(MWFSlideDirection)direction
{
    return [[BAFlyoutMenuViewController alloc] initWithNibName:@"BAFlyoutMenuViewController" bundle:nil];
}

- (NSInteger)slideNavigationViewController:(MWFSlideNavigationViewController *)controller
                  distanceForSlideDirecton:(MWFSlideDirection)direction
                       portraitOrientation:(BOOL)portraitOrientation
{
    return 270;
}

- (void)slideNavigationViewController:(MWFSlideNavigationViewController *)controller
                 willPerformSlideFor:(UIViewController *)targetController
                  withSlideDirection:(MWFSlideDirection)slideDirection
                            distance:(CGFloat)distance
                         orientation:(UIInterfaceOrientation)orientation
{
    switch (slideDirection) {
        case MWFSlideDirectionLeft:
            // This view will be partially hidden - disable user interaction.
            [self.view addSubview:transparentUserInterActionCoverView];
            transparentUserInterActionCoverView.frame = self.view.bounds;
            
            break;
        case MWFSlideDirectionNone:
            // This view is shown again - enable user interaction.
            [transparentUserInterActionCoverView removeFromSuperview];

            break;
        default:
            break;
    }

}

- (void)slideNavigationViewController:(MWFSlideNavigationViewController *)controller
                   didPerformSlideFor:(UIViewController *)targetController
                   withSlideDirection:(MWFSlideDirection)slideDirection
                             distance:(CGFloat)distance
                          orientation:(UIInterfaceOrientation)orientation
{
    switch (slideDirection) {
        case MWFSlideDirectionLeft:
            // This view has just been partially hidden - disable user interaction.
//            self.view.userInteractionEnabled = NO;
            break;
        case MWFSlideDirectionNone:
            // This view is shown again - enable user interaction.
//            self.view.userInteractionEnabled = YES;
            break;
        default:
            break;
    }
}

- (void)closeFlyoutMenu:(id)sender
{
    [self.slideNavigationViewController slideWithDirection:MWFSlideDirectionNone];
}

- (UIViewController<BAMaterialViewControllerProtocol>*)createMaterialViewController
{
    UIViewController<BAMaterialViewControllerProtocol>* matVC;
    
    if ([[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary]) {
#ifdef BA_LIBRARIAN_BUILD
        matVC = [LBLibrarianMaterialViewController new];
#endif
    } else {
        if (RD_IS_IPAD) {
            matVC = [[BAMaterialViewController alloc] initWithNibName:@"BAMaterialViewController_iPad" bundle:nil];
        } else {
            matVC = [[BAMaterialViewController alloc] initWithNibName:@"BAMaterialViewController_iPhone" bundle:nil];
        }
    }
    return matVC;
}

- (void)openUserSearchViewWithSearchString:(NSString *)searchString
{
    if (RD_IS_IPAD) {
        [rootLevelTabBarController setSelectedViewController:userSearchSlideInIPad];
        [userSearchViewControllerIPad search:searchString];
    } else {
        DLog(@"ERROR: not impl for iPhone!");
    }
}

/*
-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    DLog(@"didselect: %@, currently %@",viewController, tabBarController.selectedViewController); //were equal
}
*/

- (void)showUserGuide
{
    if (currentUserGuideViewController!=nil) {
        [currentUserGuideViewController removeFromParentViewController];
        [currentUserGuideViewController.view removeFromSuperview];
        [currentUserGuideSuperView removeFromSuperview];
    }
    
    currentUserGuideSuperView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:currentUserGuideSuperView];
    
    currentUserGuideViewController = [BAUserGuideViewController new];
    [self addChildViewController:currentUserGuideViewController];
    currentUserGuideViewController.view.frame = self.view.bounds;
    currentUserGuideViewController.view.alpha=0;
    
    
    [currentUserGuideSuperView addSubview:currentUserGuideViewController.view];
    
    [self performSelector:@selector(delayedUserGuideTransitionIn) withObject:nil afterDelay:0.1];
    
    /*
    [UIView transitionWithView:currentUserGuideViewController.view
                      duration:1.0
                       options:UIViewAnimationOptionTransitionFlipFromRight
                    animations:nil
                    completion:nil];
     */
}

- (void)delayedUserGuideTransitionIn
{
    currentUserGuideViewController.view.alpha=1;
    [UIView transitionWithView:currentUserGuideSuperView
                      duration:1
                       options:UIViewAnimationOptionTransitionCurlDown |  UIViewAnimationOptionAllowAnimatedContent
                    animations:^{
                    }
                    completion:nil];
}

- (void)dismissUserGuide:(id)sender
{
    if (currentUserGuideViewController!=nil) {
        CGRect animframe = self.view.bounds;
        animframe.origin.y -= animframe.size.height;
        [UIView animateWithDuration:0.5
                         animations:^{
                             currentUserGuideViewController.view.frame=animframe;
                             currentUserGuideViewController.view.alpha=0;
                         }
                         completion:^(BOOL finished) {
                             [currentUserGuideViewController removeFromParentViewController];
                             [currentUserGuideViewController.view removeFromSuperview];
                             currentUserGuideViewController=nil;
                             
                             [currentUserGuideSuperView removeFromSuperview];
                             currentUserGuideSuperView=nil;

                         }
         ];
        
    }
}

- (BOOL)isShowingUserGuide
{
    return (currentUserGuideViewController!=nil);
}

- (void)setPackagesCount:(NSInteger)packagesCount{
    //TODO: check for IMF editor mode
    if (packagesCount <= 0) {
        _packagesCount = 0;
    } else{
        _packagesCount = packagesCount;
    }
    UIViewController* viewController = [rootLevelTabBarController.viewControllers firstObject];
    if (viewController != nil) {
        if (_packagesCount == 0) {
            viewController.tabBarItem.badgeValue = nil;
        } else {
            viewController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", _packagesCount];
        }
        
    }
}

- (void)createIMFAddMaterialToIMFPackageViewController:(BARecord*)record delegate:(id<IMFAddMaterialToIMFPackageViewControllerDelegate>)delegate
{
#ifdef BA_IMF_BUILD
   if (RD_IS_IPAD) {
        IMFAddMaterialToIMFPackageiPadViewController* viewController = [IMFAddMaterialToIMFPackageiPadViewController new];
        viewController.delegate=delegate;
        [viewController setRecordToAdd:record];
        [self addChildViewController:viewController];
        [self.view addSubview:viewController.view];
        [BAUtils setViewToFillParent:viewController.view];
        
        
    } else {

        IMFAddMaterialToIMFPackageViewController* viewController = [IMFAddMaterialToIMFPackageViewController new];
        viewController.delegate=delegate;
        [viewController addRecordToViewController:record];
        [self presentViewController:viewController animated:YES completion:nil];
    }
#endif
}


#pragma mark UITabBarControllerDelegate
//The delegate is curently only set in IMF editor mode.
//If we need to use the delegate for somthing else, there needs to be a check for the current "app mode"

//This prevents the first tab to pop to root on the second tab press!x$
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
//    DLog(@"shouldselect: %@, currently %@",viewController, tabBarController.selectedViewController);
    UIViewController* firstTab = [tabBarController.viewControllers firstObject];
    if (firstTab == viewController && tabBarController.selectedViewController == viewController) {
        return NO;
    }
    return YES;
}


@end
